package top.mcwebsite.playandroid.business.search.impl.ui

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import top.mcwebsite.lib.route.api.EasyRouter
import top.mcwebsite.lib.router.annotation.Route
import top.mcwebsite.playandroid.business.search.impl.vm.SearchIntent
import top.mcwebsite.playandroid.business.search.impl.vm.SearchUiEffect
import top.mcwebsite.playandroid.business.search.impl.vm.SearchViewModel
import top.mcwebsite.playandroid.common.constant.RouteConfig
import top.mcwebsite.playandroid.lib.common.ext.encodeURL

@Route(RouteConfig.Search.PATH)
@Composable
fun SearchPage() {
    val viewModel: SearchViewModel = viewModel()
    val uiState by viewModel.uiStateFlow.collectAsState()
    viewModel.HandleUiEffect {
        when (it) {
            is SearchUiEffect.GoDetailPageUiEffect -> {
                EasyRouter.navigate("${RouteConfig.ArticleDetail.PATH}/${it.searchResultModel.link.encodeURL()}")
            }
        }
    }
    Scaffold {
        Column(modifier = Modifier.padding(it)) {
            SearchTopBar(
                uiState,
                onSearchKeywordChangeEvent = { searchKeyword ->
                    viewModel.sendIntent(SearchIntent.UpdateSearchKeywordIntent(searchKeyword))
                },
                backClick = {
                    EasyRouter.popBackStack()
                },
                onSearch = {
                    viewModel.sendIntent(SearchIntent.SearchActionIntent)
                }
            )
            if (uiState.searchResultPagerFlow == null) {
                SearchIntroPage(uiState = uiState) { intent ->
                    viewModel.sendIntent(intent)
                }
            } else {
                SearchResult(uiState = uiState, viewModel)
            }
        }
    }
}
